

<template>
      <el-input type="number" v-model="input" style="left:0px;width: 240px" placeholder="Please input" @input="onInput">东方</el-input>
      <div><input type="file" id="fileInput" /></div>
      
      <Vue3Lottie class="abs" v-if="state==0" ref="anim1" :autoPlay="false" :speed="2" renderer="svg" :animation-data="JSONData1" 
      @onAnimationLoaded = "onAniLoaded1"
      @onLoopComplete = "onEnd(0)" />

    <div class="div2" :style="{ transform: `scale(${screenScale})`, top:`${screenTop}px`, left:`${screenLeft}px` }">
      <el-image class="abs" src="./assets/ui/背景.png"></el-image>
      <StateButton class="back" imgSrc="./assets/ui/返回图标.png" @click="onBack"></StateButton>

      <!--<Transition>-->
        <el-image class="abs" v-if="state==1" src="./assets/ui/1静止界面/bg.jpg"></el-image>
      <!--</Transition>-->
      <StateButton class="stateButton" v-if="state==1" imgSrc="./assets/ui/1静止界面/btn.png" @click="onStart"></StateButton>

      <Vue3Lottie class="abs" style="width: 1080px;height: 1920px;" width="1080" height="1920" v-if="state==2" ref="anim1" :autoPlay="false" :speed="2" renderer="svg" :animation-data="JSONData1" 
      @onAnimationLoaded = "onAniLoaded1"
      @onLoopComplete = "onEnd(2.2)" />

      <!--2套餐页面-->
      <Vue3Lottie class="abs" v-if="state==2.2 || state==2.5" ref="animTypeIn" :autoPlay="false" :speed="2" renderer="svg" :animation-data="JSONData21" 
      @onAnimationLoaded = "onAniLoaded21"
      @onLoopComplete = "onEnd(2.6)" />

      <el-image class="abs" v-if="state==2.6 || state==2.5" src="./assets/ui/2套餐选择/背景.png"></el-image>
      <div class="abs" style="top:200px" v-if="state==2.6 || state==2.5">
        <StateButton class="stateButton2-1" v-for="item in btnList2" :imgSrc="item.src" :style="'margin-top:' + item.top + 'px'" @click="onTypeChoose($event, item.num)"></StateButton>
      </div>

      <!--3背景选择页面-->
      <Vue3Lottie class="abs" v-if="state==3" ref="animTypeOut" :autoPlay="false" :speed="2" renderer="svg" :animation-data="JSONData22" 
      @onAnimationLoaded = "onAniLoaded22" @onLoopComplete = "onEnd(3.5)" />
      <Vue3Lottie class="abs" style="width: 1080px;height: 1920px;"  height="1920px" v-if="state==3.5 || state==3.55" ref="animBgIn" :autoPlay="false" :speed="2" renderer="svg" :animation-data="JSONData31" 
      @onAnimationLoaded = "onAniLoaded31" @onLoopComplete = "onEnd(3.6)" />

      <el-image class="abs" v-if="state==3.6 || state==3.55" src="./assets/ui/3照片选择/背景.png"></el-image>
      <div class="abs" v-if="state==3.6 || state==3.55" style="top:353px">
          <StateButton class="stateButton3-1" v-for="(item, index) in btnList3" :isState2="true" :posStr="item.pos" :imgSrc="item.src" :style="'margin-top:' + item.top + 'px;' + 'margin-left:' + item.left + 'px'" @click="onBgSelect($event, index)"></StateButton>
      </div>
      <StateButton v-if="state==3.6 || state==3.55" class="stateButton3-2" imgSrc="./assets/ui/小按钮-确定.png" @click="onBgClick"></StateButton>
      <StateButton v-if="state==3.6 || state==3.55" class="btn-bg-left" imgSrc="./assets/ui/翻页按钮-左.png" @click="onBgLeftClick"></StateButton>
      <StateButton v-if="state==3.6 || state==3.55" class="btn-bg-right" imgSrc="./assets/ui/翻页按钮-右.png" @click="onBgRightClick"></StateButton>

      <NumberImg v-if="state==3.6 || state==3.55" class="num-img" regMap="0123456789/" :sourceWidth="836" :sourceHeight="84" imgSrc="./assets/ui/数字串.png" :value="bgPageStr" ></NumberImg>
      <NumberImg v-if="state==3.6 || state==3.55" class="num-img2" regMap="0123456789/" :sourceWidth="506" :sourceHeight="50" :gap="-12" imgSrc="./assets/ui/数字串-小.png" :value="bgnumstr" ></NumberImg>

      <!--4摄像头，人物页面-->
      <Vue3Lottie class="abs" style="top: -5px;" v-if="state==4" ref="animBgOut" :autoPlay="false" :speed="2" renderer="svg" :animation-data="JSONData32" 
      @onAnimationLoaded = "onAniLoaded32" @onLoopComplete = "onEnd(4.1)" />
      <Vue3Lottie class="abs" style="top: -5px;" v-if="state==4.1" ref="animRoleIn" :autoPlay="false" :speed="2" renderer="svg" :animation-data="JSONData41" 
      @onAnimationLoaded = "onAniLoaded41"
      @onLoopComplete = "onEnd(4.2)" />
      <el-image class="abs" v-if="state==4.2 || state==4.3" src="./assets/ui/4人像/背景.png"></el-image>
      <!--<video id="myvideo" v-if="state==4.1" width="320" height="240" controls>
      </video>-->
      <canvas id="mycanvas" class="canvas"  v-if="state==4.2 || state==4.3" ></canvas>
      <el-image class="abs" style="top:504px; opacity:0.6" v-if="state==4.2 || state==4.3" src="./assets/ui/4人像/虚线拍摄.png"></el-image>
      <StateButton class="stateButton4-up" v-if="state==4.2 || state==4.3" imgSrc="./assets/ui/4人像/icon-上传照片.png" ></StateButton>
      <StateButton class="stateButton4-switch" v-if="state==4.2 || state==4.3" imgSrc="./assets/ui/4人像/icon-切换模式.png" @click="on4SwitchClick"></StateButton>
      <StateButton class="stateButton4-reset" v-if="state==4.2 || state==4.3" imgSrc="./assets/ui/小按钮-重拍.png" @click="resetPhoto"></StateButton>
      <StateButton class="stateButton4-sure" v-if="state==4.2 || state==4.3" imgSrc="./assets/ui/小按钮-确定.png" @click="on4UploadClick"></StateButton>
      <StateButton class="stateButton4-flash" v-if="state==4.2 || state==4.3" imgSrc="./assets/ui/4人像/icon-点击拍照.png" @click="onTakePhoto"></StateButton>
      <el-image class="abs" style="top:409px; left:345px;" v-if="state==4.2 || state==4.3" src="./assets/ui/4人像/请沿虚线对齐身体.png"></el-image>
      <NumberImg v-if="state==4.3" class="num-photo" regMap="0123456789" :sourceWidth="2050" :sourceHeight="232" imgSrc="./assets/ui/4人像/倒计时数字串.png" :value="photoCDStr" ></NumberImg>
      <Vue3Lottie class="abs" style="top: -5px;" v-if="state==4.5" ref="animRoleOut" :autoPlay="false" :speed="1" renderer="svg" :animation-data="JSONData42" 
      @onAnimationLoaded = "onAniLoaded42" @onLoopComplete = "onEnd(4.99)" />

      <!--5进度条测试-->
      <el-image class="abs" style="top:0px; left:0px; width: 1080px;height: 1920px;" v-if="state==4.991" src="./assets/ui/5进度条/背景.png"></el-image>
      <Vue3Lottie class="abs" style="top: -5px;" v-if="state==4.99" ref="animProgressIn" :autoPlay="false" :speed="1" renderer="svg" :animation-data="JSONData51" 
      @onAnimationLoaded = "onAniLoaded51" @onLoopComplete = "onEnd(4.991)" />
      <Vue3Lottie class="abs" style="top: -5px;" v-if="state==4.992" ref="animProgressOut" :autoPlay="false" :speed="2" renderer="svg" :animation-data="JSONData52" 
      @onAnimationLoaded = "onAniLoaded52" @onLoopComplete = "onEnd(proEndState)" />
      <FrameAni class="frame-ani" v-if="state==4.99 || state==4.991" :imgArr="aniList" :opacityInTime="400"></FrameAni>
      <el-image class="abs" style="top:700px; left:354px; width: 372px;height: 173px;" v-if="state==4.991" :src="proWrodStr"></el-image>
      <div v-if="state==4.991" class="progress-container">
        <el-image class="progress-bg" src="./assets/ui/5进度条/进度条-底.png" />
        <div class="progress-bar" :style="{ width: progress + '%' }">
          <!-- 进度条内的文本内容 -->
          <span>{{ progress }}%</span>
        </div>
      </div>

      <!--6生成的照片预览界面-->
      <el-image class="abs" style="width: 1080px;height: 1920px;" v-if="state==5 || state==5.2" src="./assets/ui/6已生成图片/背景.png"></el-image>
      <el-image class="abs" style="width: 657px;height: 55px;left:200px;top:200px" v-if="state==5 || state==5.2" src="./assets/ui/6已生成图片/即可放大.png"></el-image>
      <div class="pic-div" v-if="state==5 || state==5.2" v-for="(item, index) in picList" :style="'top:'+item.top+'px; left:'+item.left+'px'">
        <el-image style="width: 250px;height: 330px;position:absolute;left:0px;top:0px" :src="item.src"></el-image>
        <el-image style="width: 53px;height: 53px;position:absolute;right:2px;top:2px" src="./assets/ui/icon-放大.png" @click="on6ClickZoom($event, index)"></el-image>
      </div>
      <StateButton class="stateButton6-make" v-if="state==5 || state==5.2" imgSrc="./assets/ui/小按钮-导出.png" @click="on6Output"></StateButton>
      
      <!--6 免费试用，单张界面-->
      <div v-if="state==5.1">
        <el-image class="abs" style="top:409px; left:345px;" src="./assets/ui/4人像/请沿虚线对齐身体.png"></el-image>
        <el-image style="width: 1000px;height: 1320px;position:absolute;left:40px;top:200px" :src="zoomImgSrc"></el-image>
        <StateButton class="stateButton4-reset" imgSrc="./assets/ui/小按钮-重拍.png" @click="onSinglePay"></StateButton>
        <StateButton class="stateButton4-sure" imgSrc="./assets/ui/小按钮-确定.png" @click="onSingleReChoose"></StateButton>
      </div>
      
      <!--6点击弹出 单张预览-->
      <div v-if="state==5.2" style="position: absolute;width: 100%; height: 100%;">
        <div style="position: absolute; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.4);" @click="onZoomMask"></div>
        <el-image style="width: 1000px;height: 1320px;position:absolute;left:40px;top:200px" :src="zoomImgSrc"></el-image>
        <StateButton class="stateButton6-make" imgSrc="./assets/ui/小按钮-重拍.png" @click="onClickZoomReset"></StateButton>
      </div>
      
      <div class="qrdiv" v-if="state==10">
        <QRCode :content="codeContent" />
        扫码进行下载
        <el-text class="qr-txt">{{ codeCDStr }}</el-text>
      </div>


    </div>

  
</template>
  


<script setup lang="ts">

import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus'

import JSONData11 from '../assets/ae2/1静止界面/data.json';
import JSONData21 from '../assets/ae2/2套餐选择/data.json';
// import JSONData from '../assets/ae2/2套餐选择 (2)/data.json';
import JSONData22 from '../assets/ae2/2套餐选择-出/data.json';
import JSONData31 from '../assets/ae2/3照片选择/data.json';
import JSONData32 from '../assets/ae2/3照片选择-出/data.json';
// import JSONData32 from '../assets/ae2/footage/data.json';
import JSONData41 from '../assets/ae2/4拍照界面/data.json';
import JSONData42 from '../assets/ae2/4拍照界面-出/data.json';
import JSONData51 from '../assets/ae2/5进度条界面/data.json';
import JSONData52 from '../assets/ae2/5进度条界面-出/data.json';

import StateButton from './components/StateButton.vue';
import NumberImg from './components/NumberImg.vue';
import FrameAni from './components/FrameAni.vue';
import QRCode from './components/QRCode.vue';

import ai_extra_data from '../assets/cfg/extra_data.json';
import ai_prompt from '../assets/cfg/prompt.json';

// import { api } from './api.js';

const client_id = 'ac2f039721094f2392c039a02ef61c0d';
// const video = ref(null);
let video:any;
let canvas:any;
let ctx:any;
let isFlash:boolean = false;
let isLock:boolean = false;

const JSONData1 = ref(JSONData11);
const input = ref(1);

const anim1 = ref(null);
const animTypeIn = ref(null);
const animTypeOut = ref(null);
const animBgIn = ref(null);
const animBgOut = ref(null);
const animRoleIn = ref(null);
const animRoleOut = ref(null);

const animProgressIn = ref(null);
const animProgressOut = ref(null);

const codeContent = ref('');
let bgnum:number = 1;
const bgnumstr = ref('');
const bgPageStr = ref('1/2');
let selectBgList:any[] = [];
let makeNum:number = 0;
let makeCount:number = 0;

const state = ref(1);
const fixWidth:number = 1080;
const fixHeight:number = 1920;
const screenHeight = ref(fixHeight);
const screenWidth = ref(fixWidth);
const screenScale = ref(1);
const screenTop = ref(0);
const screenLeft = ref(0);
const btnList2 = ref([{src:"./assets/ui/2套餐选择/高级套餐.png",top:0,num:10},{src:"./assets/ui/2套餐选择/普通套餐.png",top:108,num:5},{src:"./assets/ui/2套餐选择/免费试用.png",top:87,num:1}]);

const bgList1:any[] = [{src:"./assets/ui/3照片选择/照片1.png",source:'bg.jpg',top:0,left:84,select:false,pos:"top"},{src:"./assets/ui/3照片选择/照片2.png",source:'bg2.jpg',top:0,left:584,select:false,pos:"top"},
                    {src:"./assets/ui/3照片选择/照片3.png",source:'bg.jpg',top:450,left:84,select:false,pos:"top"},{src:"./assets/ui/3照片选择/照片4.png",source:'bg2.jpg',top:450,left:584,select:false,pos:"top"},
                    {src:"./assets/ui/3照片选择/照片5.png",source:'bg.jpg',top:900,left:84,select:false,pos:"top"},{src:"./assets/ui/3照片选择/照片6.png",source:'bg2.jpg',top:900,left:584,select:false,pos:"top"}];

const bgList2:any[] = [{src:"./assets/ui/3照片选择/照片6.png",source:'bg.jpg',top:0,left:84,select:false,pos:"top"},{src:"./assets/ui/3照片选择/照片5.png",source:'bg2.jpg',top:0,left:584,select:false,pos:"top"},
                    {src:"./assets/ui/3照片选择/照片4.png",source:'bg.jpg',top:450,left:84,select:false,pos:"top"},{src:"./assets/ui/3照片选择/照片3.png",source:'bg2.jpg',top:450,left:584,select:false,pos:"top"},
                    {src:"./assets/ui/3照片选择/照片2.png",source:'bg.jpg',top:900,left:84,select:false,pos:"top"},{src:"./assets/ui/3照片选择/照片1.png",source:'bg2.jpg',top:900,left:584,select:false,pos:"top"}];
const btnList3 = ref(bgList1);

let aniArr:string[] = [];
var aniCount = 160;
for(var i=0; i<31; i++){
  aniArr.push("./assets/ae2/5进度条界面循环动画/进度条-出_00" + aniCount + ".png");
  aniCount ++;
}
const aniList = ref(aniArr);
const progress = ref(100);
const picList = ref([{src:"./assets/ui/6已生成图片/已生成的照片.png",fileName:'',top:0,left:10}]);//ai生成的照片
let takeImg:any;
let takeImgName:any;
const photoCDStr = ref('5');
let takeCD:number = 5;
const zoomImgSrc = ref('./assets/ui/6已生成图片/已生成的照片.png');
const proEndState = ref(0);
const proWrodStr = ref('./assets/ui/5进度条/正在制作.png');
let aiHttpUrl = 'http://192.168.2.100:8189';
let makeTimeId:number = 0;
let aiBgArr:string[] = ['bg.jpg', 'bg2.jpg'];
let aiBgBlobArr:ImageLoad[] = [];
let aiBgCount:number = 0;
let aiPhotoBlobArr:ImageLoad[] = [];//最终ai生成的照片
let aiPhotoCount:number = 0;
const photoWidth:number = 1536;//设定照片尺寸
const photoHeight:number = 2048;//设定照片尺寸
let codeTimeId:number = 0;
let codeTimeId2:number = 0;
let codeCD:number = 10;
const codeCDStr = ref('');

const isMobile = ref(false);//手机
const isTablet = ref(false);//平板

resetSize();
onMounted(() => {
    // let div:any = document.getElementById("mydiv");
    window.addEventListener('resize', onResize);

    checkDeviceType();
    connectSocket();

    var input:any = document.getElementById('fileInput');
    input.addEventListener('change', function(event:any) {
        const file = event.target.files[0];
        // // 处理文件
        // console.log(files);

        // uploadFile(imgBlob);

        // makeFile(null);

        // testToLoadServer();
        scanCodeHandler();
    });
        
    //初始化上传背景图片
    setTimeout(() => {
      for(var i=0; i<aiBgArr.length; i++){
        var load:ImageLoad = new ImageLoad('./assets/test/' + aiBgArr[i], onBgLoaded);
        aiBgBlobArr.push(load);
        load.load();
      }
    }, 200);
});

 
const checkDeviceType = () => {
  const userAgent = navigator.userAgent || navigator.vendor;// || window.opera;

  if (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent)) {
    isMobile.value = true;
  } else if (/firefox|msie|trident|edge/i.test(userAgent)) {
    isTablet.value = true;
  }
};

function onBgLoaded(){
  aiBgCount ++;

  if(aiBgCount >= aiBgArr.length){
    console.log('初始化上传背景图片---->');
    var load:ImageLoad;
    for(var i=0; i<aiBgBlobArr.length; i++){
      load = aiBgBlobArr[i];
      uploadFile(load.imgBlob, aiBgArr[i]);
    }
  }
}
//加载本地的图片，转换为blob，为上传到ai服务器做准备
class ImageLoad {
  // 属性
  imgBlob:any;
  imgSrc:string = '';
  fileName:string = '';
  backFun:any;
 
  // 构造函数
  constructor(imgSrc:string, backFun:any, fileName:string='') {
    this.imgSrc = imgSrc;
    this.backFun = backFun;
    this.fileName = fileName;
  }
 
  // 方法
  load() {
    var _this = this;

    const testImg = new Image();
    testImg.crossOrigin = 'Anonymous'; // 如果图片有跨域限制
    testImg.src = _this.imgSrc;
    testImg.onload = function() {
      // 创建一个Canvas对象，并在其上绘制图片
      var canvas = document.createElement('canvas');
      canvas.width = (this as any).width;
      canvas.height = (this as any).height;
      var ctx:any = canvas.getContext('2d');
      ctx.drawImage(this, 0, 0);
  
      // 将Canvas转换为Blob数据
      canvas.toBlob(function(blob) {
        _this.imgBlob = blob;
        _this.backFun.apply();
        // console.log('图片->blob-->',blob);
      });
    }
  }
}
var imgBlob:any;
const testImg = new Image();
testImg.crossOrigin = 'Anonymous'; // 如果图片有跨域限制
testImg.src = './assets/test/p2.jpg';
testImg.onload = function() {
  // 创建一个Canvas对象，并在其上绘制图片
  var canvas = document.createElement('canvas');
    canvas.width = (this as any).width;
    canvas.height = (this as any).height;
    var ctx:any = canvas.getContext('2d');
    ctx.drawImage(this, 0, 0);
 
    // 将Canvas转换为Blob数据
    canvas.toBlob(function(blob) {

      imgBlob = blob;
      console.log('图片->blob-->',blob);
        // // 创建FormData对象
        // var formData = new FormData();
 
        // // 将Blob作为文件添加到FormData中
        // var fileName = 'image.jpg'; // 指定文件名
        // formData.append('image', blob, fileName);
 
        // 执行进一步的操作，比如使用formData发送请求等
        // ...
    });
}

async function uploadFile(img:any, fname:string){
  // makeFile('mytestimg.jpg');
  // return;

  // var fname = 'mytestimg'+Math.floor(Math.random()* 10000)+'.jpg';
  // var fname = 'bg2.jpg';
  const body = new FormData();
  body.append("image", img, fname);

  const resp = await fetch(aiHttpUrl + '/upload/image', {
    method: "POST",
    body,
  });
  console.log('uploadFile--->',resp);

  // setTimeout(() => {
  //   // makeFile(fname);
  // }, 1000);
}
async function makeFile(fname:any, bgname:string){
  var formData:any = {'client_id':client_id, 'extra_data':{}, prompt:{}};
    formData.extra_data = ai_extra_data;
    // ai_prompt[122].inputs.image = fname;

    ai_prompt[122].inputs.image = fname;//当前拍的人像照
    ai_prompt[131].inputs.image = bgname;//背景图

    ai_prompt[49].inputs.width = photoWidth;
    ai_prompt[49].inputs.height = photoHeight;

    formData.prompt = ai_prompt;

    const resp = await fetch(aiHttpUrl + "/prompt", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formData),
    });
    
    console.log('makeFile----------------------->',resp);
    
}
async function onExeStart(){
  const body = new FormData();
  body.append("message", '__start__');
  body.append("id", '-1');
  const resp2 = await fetch(aiHttpUrl + "/image_chooser_message", {
    method: "POST",
    // headers: {
    //   "Content-Type": "application/json",
    // },
    body,
  });
  console.log('makeFile2--->',resp2);
  
  // const body2 = new FormData();
  // body2.append("message", '__start__');
  // body2.append("id", '-1');
  const resp3 = await fetch(aiHttpUrl + "/easyuse/image_chooser_message", {
    method: "POST",
    // headers: {
    //   "Content-Type": "application/json",
    // },
    body,
  });
  console.log('test end2--->',resp3);
}

function onSinglePay(){
  state.value = 5.99;
}
function onSingleReChoose(){
  state.value = 2;
}
function onZoomMask(){
  state.value = 5;
}
function onClickZoomReset(){
  state.value = 4;
}
function onInput(){
  let index:number = input.value;
  if(index == 1){

  }
}
function onBack(){
  if(isLock){
    return;
  }
  let value:number = state.value;
  if(value == 10){
    state.value = 1;
    return;
  }
  value --;
  value = Math.floor(value);
  if(value < 1){
    value = 1;
  }
  state.value = value;
}
function onAniLoaded1(){
  if(anim1.value){
    (anim1.value as any).play();
    isLock = true;
  }
}
function onAniLoaded21(){
  if(animTypeIn.value){
    let ani:any = (animTypeIn.value as any);
    ani.play();
    isLock = true;
    
    console.log("animTypeIn时长：",ani.getDuration());
    setTimeout(() => {
      state.value = 2.5;
    }, 60*13.3);
  }
}
function onEnd(e:any){
  console.log("播放结束：",e);
  if(anim1.value){
    (anim1.value as any).pause();
  }
  isLock = false;
  state.value = e;

  if(e == 4.2){
    startCamera();
    resetPhoto();
  }
  if(e == 4.993){
    if(bgnum == 1){
      state.value = 5.1;
    }
    else{
      state.value = 5;
    }
  }
  if(e == 4.994){//下载二维码
    isLock = true;
    state.value = 10;
    codeTimeId = setInterval(() => {
      scanCodeHandler();
    }, 1000);
  }
}
function scanCodeHandler(){
  axios.get('http://116.62.214.126:3001/code', {}

  ).then(response => {
    // 处理响应数据
    console.log('查询扫码情况response->',response);
    const data = response.data;
    if(data.scanned){
      clearInterval(codeTimeId);

      codeCD = 10;
      codeTimeId2 = setInterval(() => {
        onCodeTimeCD();
      }, 1000);
    }
  })
  .catch(error => {
    // 处理错误情况
    console.error('查询扫码情况error->', error);
  });
}
function onCodeTimeCD(){
  codeCDStr.value = codeCD + '秒后返回初始页面';
  if(codeCD <= 0){
    
    codeCDStr.value = '';
    clearInterval(codeTimeId2);
    state.value = 1;
    isLock = false;
  }
  codeCD --;
}
function resetSize(){
  // screenHeight.value = window.innerHeight;
  let rate:number = window.innerHeight / fixHeight;
  if(isMobile.value){
    rate = window.innerWidth / fixWidth;
  }

  // screenWidth.value = fixWidth * rate;
  screenScale.value = rate;
  screenTop.value = (fixHeight - fixHeight * rate) * (-0.5);
  screenLeft.value = (fixWidth - fixWidth * rate) * (-0.5) + (window.innerWidth - fixWidth * rate) * 0.5;
  console.log("window.innerWidth="+window.innerWidth);
  console.log("位置："+fixWidth * rate);
  console.log("缩放："+rate);
}
function onResize(e:any){
  resetSize();

  
}
function onStart(e:any){
  if(anim1.value){
      (anim1.value as any).play();
      isLock = true;
    }
    
  state.value = 2;
  // state.value = 999;
}
function onTypeChoose(e:any, num:number){
  if(animTypeOut.value){
    (animTypeOut.value as any).play();
    isLock = true;
  }
  bgnum = num;
  bgnumstr.value = "0/" + num;

  state.value = 3;
  console.log("--play-->" + new Date().getTime());
}
function onAniLoaded22(){
  if(animTypeOut.value){
    (animTypeOut.value as any).play();
    isLock = true;
    
    setTimeout(() => {
      state.value = 3.5;
    }, 500);
  }
  console.log("--loaded--->" +  + new Date().getTime());
}
function onAniLoaded31(){
  if(animBgIn.value){
    (animBgIn.value as any).play();
    isLock = true;
  }
  setTimeout(() => {
      state.value = 3.55;
    }, 60*13.3);
  console.log("--loaded--->" + new Date().getTime());
}

function onBgSelect(e:any, index:number){
  let info:any = btnList3.value[index];
  let flag:boolean = !info.select;
  if(flag){
    if(selectBgList.length >= bgnum){
      ElMessage.error('超出可选张数！')
      return;
    }
    info.pos = "left bottom";
    selectBgList.push(info);
  }
  else{
    info.pos = "left top";
    selectBgList.splice(selectBgList.indexOf(info), 1);
  }
  makeNum = selectBgList.length;
  bgnumstr.value = makeNum + "/" + bgnum;

  info.select = flag;
  console.log(e);
}
function onBgClick(){

  if(selectBgList.length < 1){
    ElMessage.error('请先选择场景！')
    return;
  }
  if(animBgOut.value){
    (animBgOut.value as any).play();
    isLock = true;
  }
  state.value = 4;

}
function onBgLeftClick(){
  bgPageStr.value = "1/2";
  btnList3.value = bgList1;
}
function onBgRightClick(){
  bgPageStr.value = "2/2";
  btnList3.value = bgList2;
}
const startCamera = async () => {
  try {
    // if(video){
    //   video.play();
    //   resetPhoto();
    //   return;
    // }
    video = document.createElement("video");
    // video = document.getElementById("myvideo");

    const stream = await navigator.mediaDevices.getUserMedia({
      audio: false,
      video: true,
    });
    video.srcObject = stream;
    video.onloadedmetadata = () => {
      video.play();

      // canvas = document.createElement("canvas");
      canvas = document.getElementById("mycanvas");
      // // canvas.id = "webcam";
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;

      console.log("videoWidth="+video.videoWidth+",videoHeight="+video.videoHeight);
      // canvas.width = 1080;
      // canvas.height = 838;
      // document.body.appendChild(canvas);

      const CYAN = "#ff0000";
      ctx = canvas.getContext("2d");
      ctx.fillStyle = CYAN;
      ctx.strokeStyle = CYAN;
      ctx.lineWidth = 0.5;

      myrender();
    };

      
  } catch (error) {
    console.error('Error accessing the camera:', error);
  }
};
const resetPhoto = () => {
  isFlash = false;
  takeImg = null;
  myrender();
}
function onTakePhoto(){
  state.value = 4.3;

  isLock = true;
  takeCD = 5;
  photoCDStr.value = "5";
  const tid = setInterval( ()=> {
    takeCD --;
    if(takeCD <= 0){
      isLock = false;
      state.value = 4.2;
      clearInterval(tid);
      takePhoto();
    }
    photoCDStr.value = takeCD + "";
  }, 1000)
}
const takePhoto = async () => {
  const stream = video.srcObject;
  const track = stream.getTracks()[0];
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  const ctx = canvas.getContext('2d');

  // ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  //测试
  canvas.width = testImg.width;
  canvas.height = testImg.height;
  ctx.drawImage(testImg, 0, 0, testImg.width, testImg.height);

  canvas.toBlob(function(blob:any) {
    takeImg = blob;
  });
  
  // // 可以将canvas转换为图片，例如：base64图片
  // takeImg = canvas.toDataURL('image/png');
  takeImgName = 'photo_' + Math.floor(Math.random()*1000) + '.jpg';
  
  // 在不需要摄像头后，停止摄像头
  // track.stop();
  isFlash = true;
};
// 将数据URL转换为Blob对象
function dataURLtoBlob(dataurl:any) {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  
  return new Blob([u8arr], {type: mime});
}
function upImgToAiServer(dataURL:string){
  // 转换数据URL为Blob对象
  // const blob = dataURLtoBlob(dataURL);
  const blob = takeImg;

  //上传拍照，文件名要保存好。
  uploadFile(blob, takeImgName).then( ()=> {
    //selectBgList.length
    makeCount = 0;
    // makeNum = 2;
    makeFile(takeImgName, selectBgList[makeCount].source);
  })
}
function upImgToLoadServer(){

  var list = picList.value;
  var obj:any;
  var arr:any[] = [];
  for(var i=0; i<list.length; i++){
    obj = list[i];
    if(obj.src.indexOf('view?filename') != -1){
      arr.push(obj);
    }
  }
  const prefix = client_id;//用此做前缀
  aiPhotoCount = 0;
  for( i=0; i<arr.length; i++){
    obj = arr[i];
    // var load:ImageLoad = new ImageLoad(obj.src, onAiPhotoLoaded, obj.fileName);
    var load:ImageLoad = new ImageLoad(obj.src, onAiPhotoLoaded, i + '.png');//prefix + '_' + 
    aiPhotoBlobArr.push(load);
    load.load();
  }
}
function testToLoadServer(){
  aiPhotoCount = 0;
  var arr:any[] = [];
  for(var i=0; i<2; i++){
    arr.push({src:'./assets/test/' + aiBgArr[i], fileName:aiBgArr[i]});
  }
  let obj:any;
  for( i=0; i<arr.length; i++){
    obj = arr[i];
    var load:ImageLoad = new ImageLoad(obj.src, onAiPhotoLoaded, obj.fileName);
    aiPhotoBlobArr.push(load);
    load.load();
  }
}
function onAiPhotoLoaded(){
  aiPhotoCount ++;
  if(aiPhotoCount >= aiPhotoBlobArr.length){
    exeUpImgToLoadServer();
  }
}
function exeUpImgToLoadServer(){
  // 使用axios发送Blob对象
  const formData = new FormData();
  let imgLoad:ImageLoad;
  for(var i=0; i<aiPhotoBlobArr.length; i++){
    imgLoad = aiPhotoBlobArr[i];
    // formData.append('myfile', imgLoad.imgBlob, imgLoad.fileName); // 'image.png'是文件名
    formData.append('photos', imgLoad.imgBlob, imgLoad.fileName); // 'image.png'是文件名
  }

  //'http://192.168.2.27:3001/upload'
  //'http://116.62.214.126:3003/upload

  axios.post('http://116.62.214.126:3001/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    }
  })
  .then(response => {
    // 处理响应数据
    console.log('上传照片response->',response);
    codeContent.value = response.data;
    // state.value = 10;

    clearInterval(makeTimeId);
    state.value = 4.992;
    isLock = false;
  })
  .catch(error => {
    // 处理错误情况
    console.error('上传照片error->', error);

    codeContent.value = 'http://116.62.214.126:3003/photo?ip=11210253162';
    clearInterval(makeTimeId);
    state.value = 4.992;
    isLock = false;
  });
}
function greneratePohoto(filename:string){
  const formData = {'client_id':client_id, 'extra_data':{}, prompt:{}};
  formData.extra_data = ai_extra_data;
  ai_prompt[122].inputs.image = filename;
  formData.prompt = ai_prompt;

  axios.post('http://192.168.2.100:8189/prompt', formData, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(response => {
    // 处理响应数据
    console.log('AI生成照片response->',response);
    // codeContent.value = response.data;
    // state.value = 10;

    greneratePohoto('sdlfksdflk.jpg');
  })
  .catch(error => {
    // 处理错误情况
    console.error(error);
  });
}
function myrender(){
  if(canvas && !isFlash){

    ctx.save();
    // ctx.translate(canvas.width, 0);
    ctx.translate(0, 0);
    // ctx.scale(-1, 1);
    ctx.drawImage(
      video,
      0,
      0,
      video.videoWidth,
      video.videoHeight,
      // 1080,
      // 838,
      0,
      0,
      canvas.width,
      canvas.height
      // video.videoWidth,
      // video.videoHeight
    );
    ctx.restore();

    requestAnimationFrame(myrender);
  }
}
function onAniLoaded32(){
  if(animBgOut.value){
    (animBgOut.value as any).play();
    isLock = true;
  }
  console.log("--onAniLoaded32loaded--->" + new Date().getTime());
}
function onAniLoaded41(){
  if(animRoleIn.value){
    (animRoleIn.value as any).play();
    isLock = true;
    
    setTimeout(() => {
      state.value = 4.2;
      isLock = false;
      startCamera();
      resetPhoto();
    }, 300);
  }
  console.log("--onAniLoaded41loaded--->" + new Date().getTime());
}
function onAniLoaded42(){
  if(animRoleOut.value){
    (animRoleOut.value as any).play();
    isLock = true;
  }
}
function onAniLoaded51(){
  if(animProgressIn.value){
    (animProgressIn.value as any).play();
    isLock = true;

    setTimeout(() => {
      state.value = 4.991;
    }, 400);
  }
}
function onAniLoaded52(){
  if(animProgressOut.value){
    (animProgressOut.value as any).play();
    isLock = true;
    console.log('进度条播放')
  }
}

function on4UploadClick(){

  if(!takeImg){
    ElMessage.error('请先拍照！')
    return;
  }
  var arr = picList.value;
  for(var i=0; i<10; i++){
    arr[i] = {src:"./assets/ui/6已生成图片/照片框-小.png",fileName:'',top:0,left:10};
  }

  upImgToAiServer(takeImg);

  state.value = 4.5;
  proEndState.value = 4.993;
  isLock = true;
  
  proWrodStr.value = './assets/ui/5进度条/正在制作.png';

  showProgress();
}
function showProgress(){
  makeTimeId = setInterval(on5Progress, 33.33);
  // setTimeout(() => {
  //   //const picList = ref([{src:"./assets/ui/6已生成图片/已生成的照片.png",top:0,left:10}]);//ai生成的照片
  //   //照片排版测试。。。
  //   //do something...
  //   clearInterval(tid);

  //   // state.value = 4.5;
  //   state.value = 4.992;

  //   isLock = false;
  //   on6Init();
  // }, 3000);
}

function on6Output(){
  
  isLock = true;
  state.value = 4.5;
  proEndState.value = 4.994;
  proWrodStr.value = './assets/ui/5进度条/正在导出.png';
  showProgress2();
  upImgToLoadServer();
}
function showProgress2(){
  makeTimeId = setInterval(on5Progress, 33.33);
  // setTimeout(() => {
  //   //do something...
  //   clearInterval(tid);
  //   state.value = 4.992;

  //   isLock = false;

  // }, 3000);
}
function on5Progress(){
  var value = progress.value;
  value += 1;
  if(value > 100){
    value = 0;
  }
  progress.value = value;
}
function on4SwitchClick(){
  
}
function on6Init(){
  var arr = picList.value;
  var len = arr.length;
  var top = 300;
  var left = 100;
  var index = 0;
  if(len > 5){
    for(var i=0; i<len; i++){
      if(i >= 7){
        top = 1100;
        left = 150;
        index = i - 7;
      }
      else if(i >= 3){
        top = 700;
        left = 25;
        index = i - 3;
      }
      else{
        left = 150;
        index = i;
      }
      var obj = arr[i] ;
      obj.top = top;
      obj.left = left + (index * 260);
    }
  }
  else if(len > 1){

  }
  else{
    state.value = 5.1;
  }
  
}
function on6ClickZoom(e:any, index:number){
  state.value = 5.2;
  var item = picList.value[index];
  zoomImgSrc.value = item.src;
}

//websocket
class SocketSend {
  // 属性
  fnIndex: number;
 
  // 构造函数
  constructor() {
    this.fnIndex = 0;
  }
 
  // 方法
  start() {
    console.log(this.fnIndex,"--==-->");

    let fnIndex:number = this.fnIndex;
    const wsurl = aiHttpUrl.replace('http:', 'ws:');
    const socket = new WebSocket(wsurl + '/ws?clientId=' + client_id);
    // const socket = new WebSocket(wsurl + '/ws?clientId=' + 546546545646465);

    // 监听连接建立事件
    socket.addEventListener('open', (event) => {
      console.log('WebSocket连接已建立');
    });

    // 监听消息接收事件
    socket.addEventListener('message', (event) => {
      
      try{
        var obj = JSON.parse(event.data);
        if(obj.type == 'crystools.monitor'){
          console.log('心跳--------------->');
        }
        else{
          if(obj.type == 'executed'){
            if(obj.data.node == '190'){
              var arr = picList.value;
              const fname = obj.data.output.images[0].filename;
              const url = aiHttpUrl + '/view?filename='+fname+'&type=temp&subfolder=&t='+(Math.random()*10000);
              arr[makeCount].fileName = fname;
              arr[makeCount].src = url;
              zoomImgSrc.value = url;

              makeCount ++;
              if(makeCount >= makeNum){
                clearInterval(makeTimeId);

                // state.value = 4.5;
                isLock = false;
                setTimeout(() => {
                  state.value = 4.992;
                  on6Init();
                }, 1500);
              }
              else{
                setTimeout(() => {
                  makeFile(takeImgName, selectBgList[makeCount].source);
                }, 3000);
              }
            }
          }
          else if(obj.type == 'execution_start'){
            onExeStart();
          }
          else if(obj.type == 'execution_error'){
            // state.value = 4.1;//出错，返回拍照摄像头页面
            ElMessage.error('生成的序列照 其中有生成出错。')
          }
          console.log('收到消息：', event.data);
        }
      }
      catch(e:any){
        console.error(e);
      }
      
    });

    // 监听连接关闭事件
    socket.addEventListener('close', (event) => {
      console.log('WebSocket连接已关闭');
    });

    const send = (str:any)=> {
      // 发送消息给服务器
      socket.send(str);
    }
  }
}
function connectSocket(fnIndex:number=0)
{
  var mysocket = new SocketSend();
  mysocket.start();
  
}

</script>
<style scoped>

.pic-pre{
  position: absolute;
  width:1080px;
  height:1092px;
  background-color: rgba(0, 0, 0, 0.6);
}
.pic-div {
  position: absolute;
  width: 250px; /* 设置你想要显示的宽度 */
  height: 330px; /* 设置你想要显示的高度 */
  background-size: 100%; /* 设置背景图片的大小，这里是比容器大小多出一倍 */
  background-position: "top"; /* 设置背景图片的起始位置 */
  background-image: url("./assets/ui/6已生成图片/照片框-小.png");
  border: 1px solid red;
}
.progress-container {
  position:absolute;
  left:104px;
  top: 910px;
  width: 865px;
}
.progress-bg{
  width: 872px;
  height: 64px;
}
.progress-bar {
  position:absolute;
  left:4px;
  top: 5px;
  height: 55px; /* 进度条的高度 */
  background: linear-gradient(to right, #f39517, #ffb858); /* 渐变色 */
  border-radius: 20px; /* 圆角边框 */
  text-align: center; /* 文本水平居中 */
  line-height: 60px; /* 文本垂直居中 */
  color: white; /* 文本颜色 */
}
/* 使视频填充整个容器，可能会裁剪视频 */
video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.num-img{
  position:absolute;
  left:533px;
  top: 42px;
}
.num-img2{
  position:absolute;
  left:633px;
  top: 254px;
}
.num-photo{
  position:absolute;
  left:537px;
  top: 800px;
}
.v-enter-active,
.v-leave-active {
  transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
.qrdiv{
  position:absolute;
  width: 100%;
  height: 100%;
  text-align: center;
  font-size: 50px;
  color: white;
}
.qr-txt{
  font-size: 50px;
  color: white;
}
.canvas{
  position:absolute;
  width: 1080px;
  height: 838px;
  top:504px;
  box-sizing: border-box;
  background-color: blueviolet;
}
.abs{
  position:absolute;
  top: 0px;
  left:0px;
}
.back{
  position:absolute;
  z-index: 999;
  top: 30px;
  left: 30px;
  width: 107px;
  height: 86px;
}

.frame-ani{
  position:absolute;
  width: 992px;
  height:378px;
  left: 42px;
  bottom: 20px;
}
.btn-bg-left{
  position:absolute;
  width: 109px;
  height:119px;
  left:218px;
  top: 25px;
}
.btn-bg-right{
  position:absolute;
  width: 109px;
  height:119px;
  left:750px;
  top: 25px;
}
.stateButton6-make{
  position:absolute;
  width: 304px;
  height:114.33px;
  left:388px;
  bottom: 200px;
}
.stateButton4-up{
  position:absolute;
  width: 214px;
  height:164.33px;
  left:311px;
  top: 10px;
}
.stateButton4-switch{
  position:absolute;
  width: 214px;
  height:164.33px;
  left:605px;
  top: 10px;
}
.stateButton4-flash{
  position:absolute;
  width: 214px;
  height:164.33px;
  left:0px;
  top: 500px;
}
.stateButton4-sure{
  position:absolute;
  width: 304px;
  height:114.33px;
  left:617px;
  bottom: 370px;
}
.stateButton4-reset{
  position:absolute;
  width: 304px;
  height:114.33px;
  left:160px;
  bottom: 370px;
}
.stateButton3-2{
  position:absolute;
  width: 304px;
  height:114.33px;
  left:396px;
  bottom: 140px;
}
.stateButton3-1{
  position:absolute;
  width: 422px;
  height:381.5px;
}
.stateButton2-1{
  margin-left: 40px;
  width: 1000px;
  height:442.67px;
}
.stateButton2-2{
  position:absolute;
  left: 40px;
  top: 720px;
  width: 1000px;
  height:442.67px;
}
.stateButton2-3{
  position:absolute;
  left: 40px;
  top: 1220px;
  width: 1000px;
  height:442.67px;
}
.stateButton{
  position:absolute;
  left: 268px;
  top: 70%;
  width: 549px;
  height:199px;
}
.lottie{
  margin-top: 0px;
}
.div{
  position:absolute;
  width: 100%;
  top: 0px;
  left: 0px;
  text-align: center;
  box-sizing: border-box;
  border: 1px solid red;
  margin-top: 0px;
  padding-top: 0px;
}
.div2{
  position:absolute;
  width: 1080px;
  height: 1920px;
  box-sizing: border-box;
}
.divtest{
  position:absolute;
  width: 100%;
  height: 100%;
  top: 0px;
}
.logo {
  display: block;
  margin: 0 auto 2rem;
}

</style>
